
package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.ProcessStep;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.VendorLocationDAO;
import com.scalar.chiptrack.operations.process.dao.WaferStoreDAO;
import com.scalar.chiptrack.operations.process.dao.ProcessTrackDAO;
import com.scalar.chiptrack.operations.process.forms.WaferStoreForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;

public class WaferStoreAction extends ChipTrackAction {

    public WaferStoreAction() {
    }

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception {


        String STEP_TYPE = "Wafer Store";
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}
        String action = request.getParameter("action");

        if ((action != null) && (action.equalsIgnoreCase("save")))
        {
            DBTransaction dbTransaction = null;
            boolean success = false;

            WaferStoreForm wsForm = (WaferStoreForm) form;

            HashMap errors = validateForm (wsForm);
            if ((errors != null) && (errors.isEmpty() == false))
            {
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
            else
            {
                int processStepId = -1;
				processStepId = wsForm.getProcessStepId();

                // added by ravikanth on 17 Aug 2003 to check for duplicate part numbers in Product Map Table
				String[] partNumbers = new String[wsForm.getDupProductName().length+1];
				partNumbers[0] = wsForm.getProductName();
				for(int i=0; i < wsForm.getDupProductName().length ; i++)
				{
					partNumbers[i+1] = wsForm.getDupProductName()[i];
				}
				// added by ravikanth on 16 Sep 2003
				// check for duplicates in Product_Map_Table
				String dupNames = ProductDao.checkDupInProductMapTable(partNumbers,processStepId,STEP_TYPE);
				if( dupNames.length() > 0 )
				{
					ArrayList vendorLocations = null;
					errors.put ("Part Numbers Already exists ", dupNames );

                    // changed by hareesh on 27th Septemeber 2000
                    // -- START --
                    vendorLocations =  getAllVendorLocations(request);
                    if(vendorLocations == null){
					    if(processStepId!=-1)
					    {
						    vendorLocations = VendorDAO.getWaferStoreLocations (processStepId);
					    }
					    else
					    {
						    vendorLocations = VendorDAO.getWaferStoreLocations();
					    }
                    }
                    // -- END --

					request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
					request.setAttribute( "waferStoreForm" , wsForm );
					request.setAttribute( "vendorLocations" , vendorLocations );
					return ( mapping.findForward("failure") );
				}
                // upto here
                try
                {
                    // start transaction
                    dbTransaction = DBTransaction.getInstance();
                    dbTransaction.begin();
					ArrayList locations = getVendorLocations(request);

					//System.out.println("processStepId in ws "+processStepId);
					if(processStepId==-1)         // save new process step
					{
						// Step 1
						// insert a record into Process_Step table and get the process step id
						processStepId = ProcessStep.getProcessStepID (dbTransaction, STEP_TYPE, STEP_TYPE, wsForm.getComments());

						// Step 2
						// Store Product Table information
						ProductDao.saveProcessStepProduct (dbTransaction,
												   processStepId,
												   wsForm.getProductName(),
												   wsForm.getBaseProductId());

						// Step 3
						// insert a row in Inventory_Step table
						WaferStoreDAO.storeWaferStoreData (dbTransaction, processStepId, wsForm);

						// Step 4
						// Update nextStepID in the previousStepID row
						ProductDao.updateNextProcessStepId (dbTransaction, wsForm.getPreviousStepId(), processStepId);

						// Step 5
						// Save vendor locations

						if ((locations != null) && (locations.size() > 0))
						{
							VendorLocationDAO.saveVendorLocations (dbTransaction, processStepId, locations.iterator());
						}

						// Added by ravikanth on 17 Sep 2003
						// Step 6
						// Save Duplicate names into Product_Map_Table

						if( wsForm.getDupProductName() != null && wsForm.getDupProductName().length > 0)
						{
							ProductDao.saveProductMap( dbTransaction , processStepId , wsForm.getDupProductName() , locations );
						}

                        // Added by hareesh on 3rd October 2003
                        // Step 7
                        // Change Status from Incomplete -> InProcess
                         ProcessTrackDAO.updateSortAndWaferStoreTrack( dbTransaction, processStepId , wsForm.getTrackID() , wsForm.getStepName(), "Inprocess" );

                    }
					else		// update the existing process Step
					{
						//Step 1
						//Update Process_Step table
						ProcessStep.updateProcessStepID(dbTransaction,STEP_TYPE,STEP_TYPE,wsForm.getComments(),processStepId);

						//Step 2
						//Update Product table
						ProductDao.updateProcessStepProduct(dbTransaction,processStepId,wsForm.getProductName(),
												   wsForm.getBaseProductId());

						//Step 3
						//Update Inventory_Step table
						WaferStoreDAO.updateWaferStoreData (dbTransaction, processStepId, wsForm);
						// Step 4
    					// Update vendor locations
                        //Added by hareesh on 25th Septemeber 2003
	    		        VendorLocationDAO.deleteVendorLocations(dbTransaction,processStepId);

						if ((locations != null) && (locations.size() > 0)) {
                            // changed by hareesh on 25th Septemeber 2003
                            //VendorLocationDAO.deleteVendorLocations(dbTransaction,processStepId);
							VendorLocationDAO.saveVendorLocations (dbTransaction, processStepId, locations.iterator());
						}

						// Added by ravikanth on 17 Sep 2003
						// Step 5
						// Save Duplicate names into Product_Map_Table
						if( wsForm.getDupProductName() != null && wsForm.getDupProductName().length > 0)
						{
							ProductDao.saveProductMap( dbTransaction , processStepId , wsForm.getDupProductName() , locations );
						}

				    }
                    // End transaction

                    success = true;
                }
                catch (ScalarException se)
                {
                    // exception while storing Wafer Store information into databse
                    se.getRootCause().printStackTrace();
                }
                finally
                {
                    // Rollback or Commit the Transaction
                    if (success == true) {
                        dbTransaction.commit();
                    }
                    else {
                        dbTransaction.rollback();
                    }
                }

                request.setAttribute ("processStepId", processStepId+"");                   //
                request.setAttribute ("previousStepId", wsForm.getPreviousStepId()+"");   // to be used in transport_locations page
                request.setAttribute ("trackId", wsForm.getTrackID()+"");                  //
                request.setAttribute ("productName", wsForm.getProductName());            //
                request.setAttribute ("stepName", wsForm.getStepName());                   //
                request.setAttribute ("baseProductId", wsForm.getBaseProductId()+"");       //
                request.setAttribute ("comingFrom", "WAFER_STORE");                        //
            }

            if (success == true) {
                return (mapping.findForward ("success"));
            }

            // changed by hareesh on 27th September 2003
            // -- START --
            //ArrayList vendorLocations = VendorDAO.getDieBankLocations();
            ArrayList vendorLocations = null;
            vendorLocations =  getAllVendorLocations(request);
            if( vendorLocations == null ) {
                int processStepId = -1;
				processStepId = wsForm.getProcessStepId();
                if(processStepId != -1)
                {
                    vendorLocations = VendorDAO.getWaferStoreLocations (processStepId);
                }
                else
                {
                    vendorLocations = VendorDAO.getWaferStoreLocations();
                }
            }

            //ArrayList vendorLocations = VendorDAO.getWaferStoreLocations();
            request.setAttribute("vendorLocations", vendorLocations);
            // -- END --
            return (mapping.findForward ("failure"));
        }

        int processStepId = Integer.parseInt (request.getParameter ("processStepID"));
        int trackId = -1;
        String trackIdStr = request.getParameter ("trackID");
        if ((trackIdStr != null) && (trackIdStr.trim().length() != 0))
        {
            trackId = Integer.parseInt (trackIdStr);
        }

        WaferStoreForm wsForm = null;
        ArrayList vendorLocations = null;

        if (processStepId == -1)		// New
        {
            String stepName = request.getParameter ("stepName");
            String productName = request.getParameter ("productName");
            int baseProductId = Integer.parseInt (request.getParameter ("baseProductID"));
            int previousStepId = Integer.parseInt (request.getParameter ("previousStepID"));

            wsForm = new WaferStoreForm();
            wsForm.setTrackID (trackId);
            wsForm.setStepName (stepName);
            wsForm.setProductName (productName);
            wsForm.setBaseProductId (baseProductId);
            wsForm.setPreviousStepId (previousStepId);

            vendorLocations = VendorDAO.getWaferStoreLocations();
        }
        else		// Existing
        {
            wsForm = WaferStoreDAO.loadWaferStoreData (processStepId);
            wsForm.setTrackID (trackId);
            wsForm.setProcessStepId (processStepId);
            vendorLocations = VendorDAO.getWaferStoreLocations (processStepId);
        }

        request.setAttribute ("vendorLocations", vendorLocations);
        request.setAttribute ("waferStoreForm", wsForm);

        return (mapping.findForward("show"));
    }


    private HashMap validateForm (WaferStoreForm wsForm) {

        HashMap errors = new HashMap();

        try
        {
            Integer.parseInt (wsForm.getMaxLevel());
        }
        catch (NumberFormatException nfe)
        {
            errors.put ("Max Level", "Invalid number entered for Max Level");
        }

        try
        {
            Integer.parseInt (wsForm.getMinLevel());
        }
        catch (NumberFormatException nfe)
        {
            errors.put ("Min Level", "Invalid number entered for Min Level");
        }

        try
        {
            Integer.parseInt (wsForm.getMaxTime());
        }
        catch (NumberFormatException nfe)
        {
            errors.put ("Max Time", "Invalid number entered for Max Time");
        }

        return errors;
    }


    private ArrayList getVendorLocations (HttpServletRequest request) {

        ArrayList vendorLocations = new ArrayList();

        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null)
        {
            return null;
        }

		String[] priority = request.getParameterValues("priority");
		String[] locationID = request.getParameterValues("locationID");;

        VendorLocation location = null;
        String select = null;

        for (int i=0; i<locationName.length; i++)
        {
            select = request.getParameter("select_"+i);
            if (select != null) {    // check if this row was enabled by the user or not
                                     // save only if its enabled

                location = new VendorLocation ( select,
                                                //priority[i],
                                                // changed by hareesh on 25th August 2003 // not get -1's if value not entered
                                                ( priority[i] !=null && priority[i].trim().length() != 0 ? priority[i] : "0" ),
                                                locationName[i],
                                                locationID[i] );
                vendorLocations.add (location);
            }
        }
        return vendorLocations;
    }
    // added by hareesh on 27th Septemeber 2003
    // -- START --
    private ArrayList getAllVendorLocations (HttpServletRequest request) {

        ArrayList vendorLocations = new ArrayList();

        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null)
        {
            return null;
        }

		String[] priority = request.getParameterValues("priority");
		String[] locationID = request.getParameterValues("locationID");;

        VendorLocation location = null;
        String select = null;

        for (int i=0; i<locationName.length; i++)
        {
           select = request.getParameter("select_"+i);
            if (select != null) {    // check if this row was enabled by the user or not
                 select = "on";                    // save only if its enabled
            }else {
              select = "";
            }
            location = new VendorLocation ( select,
                                           ( priority[i] !=null && priority[i].trim().length() != 0 ? priority[i] : "0" ),
                                            locationName[i],
                                            locationID[i] );
                vendorLocations.add (location);

        }
        return vendorLocations;
    }
    // -- END --

}